/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.facedoor.modular.orgdevice.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.facedoor.modular.baseEntity.IdNameBar;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.service.DeviceBaseService;
import vip.xiaonuo.facedoor.modular.memberdevice.constant.MemberDeviceConstant;
import vip.xiaonuo.facedoor.modular.memberdevice.entity.MemberDevice;
import vip.xiaonuo.facedoor.modular.memberdevice.mapper.MemberDeviceMapper;
import vip.xiaonuo.facedoor.modular.memberdevice.service.MemberDeviceService;
import vip.xiaonuo.facedoor.modular.memberuser.entity.MemberUser;
import vip.xiaonuo.facedoor.modular.memberuser.mapper.MemberUserMapper;
import vip.xiaonuo.facedoor.modular.orgdevice.entity.OrgDevice;
import vip.xiaonuo.facedoor.modular.orgdevice.mapper.OrgDeviceMapper;
import vip.xiaonuo.facedoor.modular.orgdevice.param.BatchSaveOrgParam;
import vip.xiaonuo.facedoor.modular.orgdevice.param.OrgDeviceParam;
import vip.xiaonuo.facedoor.modular.tanscation.TranCationCallBackService;
import vip.xiaonuo.facedoor.modular.visitordevice.entity.VisitorDevice;
import vip.xiaonuo.facedoor.modular.visitordevice.mapper.VisitorDeviceMapper;
import vip.xiaonuo.facedoor.modular.visitordevice.service.VisitorDeviceService;
import vip.xiaonuo.facedoor.modular.orgdevice.service.OrgDeviceService;
import vip.xiaonuo.facedoor.modular.visitor.entity.Visitor;
import vip.xiaonuo.facedoor.modular.visitor.mapper.VisitorMapper;
import vip.xiaonuo.sys.modular.org.entity.SysOrg;
import vip.xiaonuo.sys.modular.org.mapper.SysOrgMapper;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 组织关联设备表service接口实现类
 *
 * @author 胡鹏达
 * @date 2022-07-11 17:45:10
 */
@Service
public class OrgDeviceServiceImpl extends ServiceImpl<OrgDeviceMapper, OrgDevice> implements OrgDeviceService {


    @Resource
    private DeviceBaseService deviceBaseService;

    @Resource
    private SysOrgMapper sysOrgMapper;

    @Resource
    private OrgDeviceMapper orgDeviceMapper;

    @Resource
    private MemberDeviceMapper memberDeviceMapper;

    @Resource
    private MemberDeviceService memberDeviceService;

    @Resource
    private MemberUserMapper memberUserMapper;

    @Resource
    private VisitorDeviceService visitorDeviceService;

    @Resource
    private VisitorDeviceMapper visitorDeviceMapper;

    @Resource
    private VisitorMapper visitorMapper;

    @Resource
    private TranCationCallBackService callBackService;

    @Override
    public List<OrgDevice> list(OrgDeviceParam orgDeviceParam) {
        return this.list(new LambdaQueryWrapper<OrgDevice>().eq(OrgDevice::getDeviceId, orgDeviceParam.getDeviceId()));
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSave(BatchSaveOrgParam param) {

        DeviceBase byId = deviceBaseService.getById(param.getDeviceId());
        if (ObjectUtil.equal(byId.getDeviceSyncStatus(), 2)) {
            throw new ServiceException(500, "处理上次人员变更中,请稍后重试!");
        }

        if (!ObjectUtil.equal(byId.getDeviceState(), "1")) {
            throw new ServiceException(500, "设备未在线！");
        }

        if (!ObjectUtil.equal(byId.getDeviceState(), "1")) {
            throw new ServiceException(500, "设备已经断线!");
        }

        baseCheck(param);

        byId.setDeviceSyncStatus(1);
        deviceBaseService.updateById(byId);

        List<SysOrg> memberOrgs = new ArrayList<>();
        memberOrgs.add(new SysOrg().setId(-1L));
        List<SysOrg> visitorOrgs = new ArrayList<>();
        visitorOrgs.add(new SysOrg().setId(-1L));

        // 设置默认值方便下面做比较 防止产生空指针异常
        if (CollectionUtils.isEmpty(param.getOrgIds())) {
            param.setOrgIds(new ArrayList<>());
        }

        if (!CollectionUtils.isEmpty(param.getOrgIds())) {
            // 人员组织
            memberOrgs = sysOrgMapper.selectList(new LambdaQueryWrapper<SysOrg>().ne(SysOrg::getType, 2).in(SysOrg::getId, param.getOrgIds()));

            // 访客组织
            visitorOrgs = sysOrgMapper.selectList(new LambdaQueryWrapper<SysOrg>().ne(SysOrg::getType, 1).in(SysOrg::getId, param.getOrgIds()));
        }

        // 数据库人员的
        List<SysOrg> dbMemberOrgs = new ArrayList<>();
        List<SysOrg> dbvisitorOrgs = new ArrayList<>();
        List<OrgDevice> orgDevices = orgDeviceMapper.selectList(new LambdaQueryWrapper<OrgDevice>().eq(OrgDevice::getDeviceId, param.getDeviceId()));
        List<Long> dbOrgIds = orgDevices.stream().map(OrgDevice::getOrgId).distinct().collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(dbOrgIds)) {
            dbMemberOrgs = sysOrgMapper.selectList(new LambdaQueryWrapper<SysOrg>().ne(SysOrg::getType, 2).in(SysOrg::getId, dbOrgIds));
            dbvisitorOrgs = sysOrgMapper.selectList(new LambdaQueryWrapper<SysOrg>().ne(SysOrg::getType, 1).in(SysOrg::getId, dbOrgIds));
        }

        // 删除当前设备原全部关联关系
        this.remove(new LambdaQueryWrapper<OrgDevice>().eq(OrgDevice::getDeviceId, param.getDeviceId()));

        // 新增当前设备全部关联关系
        ArrayList<OrgDevice> objects = Lists.newArrayList();
        for (Long orgId : param.getOrgIds()) {
            objects.add(new OrgDevice().setDeviceId(param.getDeviceId()).setOrgId(orgId));
        }
        this.saveBatch(objects);

        // 事务处理
        List<SysOrg> tmemberOrgs = memberOrgs;
        List<SysOrg> tvisitorOrgs = visitorOrgs;
        List<SysOrg> tdbMemberOrgs = dbMemberOrgs;
        List<SysOrg> tdbvisitorOrgs = dbvisitorOrgs;
        callBackService.execute(() -> {
            OrgDeviceService orgDeviceService = (OrgDeviceService) AopContext.currentProxy();
            orgDeviceService.executeMemberAndVisitorSync(param, tmemberOrgs, tvisitorOrgs, tdbMemberOrgs, tdbvisitorOrgs);

        });
    }

    @Async
    @Override
    @Transactional
    public void executeMemberAndVisitorSync(BatchSaveOrgParam param, List<SysOrg> memberOrgs, List<SysOrg> visitorOrgs, List<SysOrg> dbMemberOrgs, List<SysOrg> dbvisitorOrgs) {
        executeMemberDevice(param.getDeviceId(), memberOrgs, dbMemberOrgs);

        executeVisitorDevice(param.getDeviceId(), visitorOrgs, dbvisitorOrgs);

        DeviceBase byId = deviceBaseService.getById(param.getDeviceId());

        byId.setDeviceSyncStatus(1);
        deviceBaseService.updateById(byId);

    }


    public void executeMemberDevice(Long deviceId, List<SysOrg> memberOrgs, List<SysOrg> dbSysOrg) {

        List<Long> memberOrgIds = memberOrgs.stream().map(SysOrg::getId).collect(Collectors.toList());

        // 目前已经存在数据库里面的
        List<Long> orgIds = dbSysOrg.stream().map(SysOrg::getId).collect(Collectors.toList());

        // 新增的组织
        List<Long> addTempList = new ArrayList(memberOrgIds);
        addTempList.removeAll(orgIds);
        List<Long> addOrgIds = addTempList;

        // 删除的组织
        orgIds.removeAll(memberOrgIds);
        List<Long> deleteOrgIds = orgIds;

        List<MemberDevice> memberDevices = new ArrayList<>();
        for (Long addOrgId : addOrgIds) {
            // 查询组织下的所有人员
            List<MemberUser> memberUsers = memberUserMapper.selectList(new LambdaQueryWrapper<MemberUser>().eq(MemberUser::getOrgId, addOrgId));
            for (MemberUser memberUser : memberUsers) {
                // 该组织 该人员下的设备信息
                MemberDevice memberDevice = memberDeviceMapper.selectOne(new LambdaQueryWrapper<MemberDevice>().eq(MemberDevice::getMemberId, memberUser.getId()).eq(MemberDevice::getDeviceId, deviceId).eq(MemberDevice::getOrgId, addOrgId));
                // 新增
                if (memberDevice == null) {
                    MemberDevice saveBean = new MemberDevice().setMemberId(memberUser.getId()).setDeviceId(deviceId).setOrgId(addOrgId).setStatus(MemberDeviceConstant.ADD);
                    memberDevices.add(saveBean);
                }
            }
        }
        List<List<MemberDevice>> partition = ListUtils.partition(memberDevices, 300);
        for (List<MemberDevice> devices : partition) {
            memberDeviceService.saveBatch(devices);
        }

        if (CollectionUtils.isNotEmpty(deleteOrgIds)) {
            // 修改为删除任务,并且不修改存储柜的管理员
            memberDeviceService.update(new LambdaUpdateWrapper<MemberDevice>().set(MemberDevice::getStatus, MemberDeviceConstant.DELETE).eq(MemberDevice::getDeviceId, deviceId).in(MemberDevice::getOrgId, deleteOrgIds));
        }

    }


    public void executeVisitorDevice(Long deviceId, List<SysOrg> visitorOrgs, List<SysOrg> dbvisitorOrgs) {

        List<Long> visitorOrgIds = visitorOrgs.stream().map(SysOrg::getId).collect(Collectors.toList());

        // 目前已经存在数据库里面的
        List<Long> orgIds = dbvisitorOrgs.stream().map(SysOrg::getId).collect(Collectors.toList());

        // 新增的组织
        List<Long> addTempList = new ArrayList(visitorOrgIds);
        addTempList.removeAll(orgIds);
        List<Long> addOrgIds = addTempList;

        // 删除的组织
        orgIds.removeAll(visitorOrgIds);
        List<Long> deleteOrgIds = orgIds;

        List<VisitorDevice> visitorDevices = new ArrayList<>();

        for (Long addOrgId : addOrgIds) {
            // 查询组织下的所有人员
            List<Visitor> visitors = visitorMapper.selectList(new LambdaQueryWrapper<Visitor>().eq(Visitor::getOrgId, addOrgId));
            for (Visitor visitor : visitors) {
                // 该组织 该人员下的设备信息
                VisitorDevice memberDevice = visitorDeviceMapper.selectOne(new LambdaQueryWrapper<VisitorDevice>().eq(VisitorDevice::getVisitorId, visitor.getId()).eq(VisitorDevice::getDeviceId, deviceId).eq(VisitorDevice::getOrgId, addOrgId));
                // 新增
                if (memberDevice == null) {
                    VisitorDevice saveBean = new VisitorDevice().setVisitorId(visitor.getId()).setDeviceId(deviceId).setOrgId(addOrgId).setStatus(MemberDeviceConstant.ADD);
                    visitorDevices.add(saveBean);
                }
            }
        }

        List<List<VisitorDevice>> partition = ListUtils.partition(visitorDevices, 300);
        for (List<VisitorDevice> devices : partition) {
            visitorDeviceService.saveBatch(devices);
        }

        if (CollectionUtils.isNotEmpty(deleteOrgIds)) {
            // 修改为删除任务
            visitorDeviceService.update(new LambdaUpdateWrapper<VisitorDevice>().set(VisitorDevice::getStatus, MemberDeviceConstant.DELETE).eq(VisitorDevice::getDeviceId, deviceId).in(VisitorDevice::getOrgId, deleteOrgIds));
        }
    }

    private void baseCheck(BatchSaveOrgParam param) {
        DeviceBase byId = deviceBaseService.getById(param.getDeviceId());
        if (!ObjectUtil.equal(byId.getDeviceType(), "4")) {
            long visitorCount = visitorDeviceMapper.selectCount(new LambdaQueryWrapper<VisitorDevice>().eq(VisitorDevice::getDeviceId, param.getDeviceId()).in(VisitorDevice::getStatus, MemberDeviceConstant.ADD, MemberDeviceConstant.UPDATE, MemberDeviceConstant.DELETE));
            if (visitorCount > 0) {
                throw new ServiceException(500, "设备忙碌中！请稍后!");
            }
        }
        long memberCount = memberDeviceMapper.selectCount(new LambdaQueryWrapper<MemberDevice>().eq(MemberDevice::getDeviceId, param.getDeviceId()).in(MemberDevice::getStatus, MemberDeviceConstant.ADD, MemberDeviceConstant.UPDATE, MemberDeviceConstant.DELETE));
        if (memberCount > 0) {
            throw new ServiceException(500, "设备忙碌中！请稍后!");
        }
    }

    @Override
    public List<IdNameBar> getDeviceNameByOrgId(Long orgId) {
        return orgDeviceMapper.selectDeviceNameByOrgId(orgId);
    }
}
